import { Http } from "../utils/http";

// 分页数据类
class Paging {
  // 属性
  req;
  start;
  count;
  locker = false;
  url; // 原始url ， 避免传值中url带有?xxxx=xxx
  moreData = true; // 当前是否更多数据
  accumulator = []; // 累加数据
  // 构造函数
  constructor(req, count = 10, start = 0) {
    this.req = req;
    this.start = start;
    this.count = count;
    this.url = req.url;
  }
  // 获取更多数据
  async getMoreData() {
    if (!this.moreData) {
      return;
    }
    if (!this._getLocker()) {
      return;
    }
    const data = await this._actualGetData();
    this._releaseLocker();
    return data;
  }

  // 获取数据
  async _actualGetData() {
    const request = this._getCurrentRequest();
    let paging = await Http.request(request);
    if (!paging) {
      return null;
    }
    if (paging.total === 0) {
      return {
        empty: true, //数据是否为空
        items: [], // 具体数据列表
        moreData: false, // 是否有更多数据
        accumulator: [], //所有请求的历史数据
      };
    }

    // 判断是否还有数据
    this.moreData = this._moreData(paging.total_page, paging.page);
    if (this.moreData) {
      this.start += this.count;
    }
    this._accumulator(paging.items);

    return {
      empty: false,
      items: paging.items,
      moreData: this.moreData,
      accumulator: this.accumulator,
    };
  }
  _accumulator(items) {
    this.accumulator = this.accumulator.concat(items);
  }

  _moreData(totalPage, pageNum) {
    return pageNum < totalPage - 1;
  }

  // 处理当前请求参数
  _getCurrentRequest() {
    let url = this.url;
    const params = `start=${this.start}&count=${this.count}`;
    // 链接包含参数校验
    if (url.includes("?")) {
      url += "&" + params;
    } else {
      url += "?" + params;
    }
    this.req.url = url;
    return this.req;
  }
  // 获取锁状态
  _getLocker() {
    if (this.locker) {
      return false;
    }
    this.locker = true;
    return true;
  }

  // 释放锁
  _releaseLocker() {
    this.locker = false;
  }
}
export { Paging };
